import { useTestResults } from '@/contexts/TestResultsContext';
import { useAudioPlayer } from 'expo-audio';
import { useNavigation } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';

interface ReactionTestProps {
}

const ReactionDevice: React.FC<ReactionTestProps> = () => {
    const [testState, setTestState] = useState<'idle' | 'countdown' | 'waiting' | 'testing' | 'finished'>('idle');
    const [countdown, setCountdown] = useState(3);
    const [currentColor, setCurrentColor] = useState<'red' | 'green' | 'blue' | 'yellow' | null>(null);
    const [testCount, setTestCount] = useState(0);
    const [reactionTimes, setReactionTimes] = useState<number[]>([]);
    const [startTime, setStartTime] = useState(0);
    const [averageTime, setAverageTime] = useState(0);
    const [showError, setShowError] = useState(false);
    const [showCompletionDialog, setShowCompletionDialog] = useState(false);

    const {addTestResult} = useTestResults();
    const navigation = useNavigation();
    
    // 使用 useAudioPlayer hook 创建音频播放器
    const audioSource = require('../../assets/mp3/notice.mp3');
    const player = useAudioPlayer(audioSource);

    const playNotificationSound = () => {
        try {
            // 重置到开头并播放
            player.seekTo(0);
            player.play();
        } catch (error) {
            console.error('Error playing sound:', error);
        }
    };

    const handleTestComplete = () => {
        // 显示检测完成提示对话框
        setShowCompletionDialog(true);
        // 播放完成提示音
        playNotificationSound();
    };
    
    const colors = ['red', 'green', 'blue', 'yellow'] as const;
    const colorNames = {red: '红色', green: '绿色', blue: '蓝色', yellow: '黄色'};
    const colorValues = {red: '#FF4444', green: '#44FF44', blue: '#4444FF', yellow: '#FFDD44'};

    const startTest = () => {
        setTestState('countdown');
        setCountdown(3);
        setTestCount(0);
        setReactionTimes([]);
        setAverageTime(0);
    };

    const handleColorClick = (color: 'red' | 'green' | 'blue' | 'yellow') => {
        if (testState !== 'testing' || !currentColor) return;

        const reactionTime = Date.now() - startTime;

        if (color === currentColor) {
            // 只有点击正确时才记录反应时间
            let newReactionTimes = [...reactionTimes, reactionTime];
            setReactionTimes(newReactionTimes);

            if (testCount < 9) {
                setTestCount(testCount + 1);
                setTestState('waiting');
                // 随机等待1-3秒后显示下一个颜色
                const waitTime = Math.random() * 2000 + 1000;
                setTimeout(() => showRandomColor(), waitTime);
            } else {
                // 去掉两个最大值后求平均值
                newReactionTimes = newReactionTimes.sort((a, b) => a - b);
                const avg = (newReactionTimes.reduce((a, b) => a + b, 0) - newReactionTimes[newReactionTimes.length - 1] - newReactionTimes[newReactionTimes.length - 2]) / (newReactionTimes.length - 2);
                setAverageTime(avg);
                setTestState('finished');

                // 保存测试结果
                const status = avg < 1000 ? 'normal' : avg < 2000 ? 'warning' : 'danger';
                console.log('保存反应时测试结果:', {
                    measurement: {
                        value: Math.round(avg),
                        unit: 'ms'
                    },
                    status,
                    completedAt: new Date(),
                    details: {
                        allTimes: newReactionTimes,
                        testCount: 10
                    }
                });
                addTestResult('Reaction', '反应时测试仪', {
                    value: Math.round(avg),
                    unit: 'ms',
                    rawData: JSON.stringify(newReactionTimes),
                    timestamp: new Date().toISOString()
                });

                // 显示检测完成提示对话框
                handleTestComplete();
            }
        } else {
            // 点击错误，显示错误提示并重新开始当前测试
            setShowError(true);
            setTestState('waiting');
            setTimeout(() => {
                setShowError(false);
                showRandomColor();
            }, 1500);
        }
    };

    const showRandomColor = () => {
        const randomColor = colors[Math.floor(Math.random() * colors.length)];
        setCurrentColor(randomColor);
        setStartTime(Date.now());
        setTestState('testing');
    };

    const finishTest = () => {
        setShowCompletionDialog(false);
        navigation.goBack();
    };

    useEffect(() => {
        let timer: number | undefined = undefined;

        if (testState === 'countdown') {
            timer = setInterval(() => {
                setCountdown(prev => {
                    if (prev <= 1) {
                        if (timer) clearInterval(timer);
                        setTestState('waiting');
                        // 开始第一个测试前等待1-3秒
                        const waitTime = Math.random() * 2000 + 1000;
                        setTimeout(() => showRandomColor(), waitTime);
                        return 0;
                    }
                    return prev - 1;
                });
            }, 1000);
        }

        return () => {
            if (timer) clearInterval(timer);
        };
    }, [testState]);

    const text = `                     
    1. 点击"开始测试"按钮
    2. 当屏幕显示颜色时，尽快点击对应按钮
    3. 总共进行10次测试
    4. 系统将计算您的平均反应时间
    `

    const className = 'mb-12 w-28 h-28 rounded-full justify-center items-center shadow-lg flex-1 max-w-[120px]'
    return (
        <SafeAreaView className="flex-1 bg-gray-50">
            <View className="bg-[#0a7ea4] pt-5 pb-5 px-5 items-center">
                <Text className="text-2xl font-bold text-white mb-2">反应时测试</Text>
                <Text className="text-base text-white/90 text-center leading-6">
                    当屏幕显示颜色时，请尽快点击对应的颜色按钮
                </Text>
            </View>

            <View className="flex-1 justify-center items-center p-5">
                {testState === 'idle' && (
                    <View className="items-center">
                        <Text className="text-2xl text-gray-800 leading-6 mb-8 bg-white p-5 rounded-xl shadow-sm">
                            测试说明
                        </Text>
                        <Text
                            className="text-2xl text-gray-800 leading-6 mb-8 bg-white p-5 rounded-xl shadow-sm">
                            {text}
                        </Text>
                        <TouchableOpacity className="bg-[#0a7ea4] px-10 py-4 rounded-xl" onPress={startTest}>
                            <Text className="text-white text-lg font-bold">开始测试</Text>
                        </TouchableOpacity>
                    </View>
                )}

                {testState === 'countdown' && (
                    <View className="items-center">
                        <Text className="text-2xl text-gray-800 mb-5">准备开始</Text>
                        <Text className="text-7xl font-bold text-blue-600">{countdown}</Text>
                    </View>
                )}

                {testState === 'waiting' && (
                    <View className="items-center">
                        {showError ? (
                            <>
                                <View className="bg-red-100 border-2 border-red-400 rounded-xl p-6 mb-5">
                                    <Text className="text-3xl text-red-600 font-bold text-center mb-2">❌</Text>
                                    <Text className="text-xl text-red-700 font-bold text-center mb-2">点击错误！</Text>
                                    <Text className="text-base text-red-600 text-center">请点击正确的颜色按钮</Text>
                                </View>
                                <Text className="text-lg text-blue-600 font-bold">
                                    第 {testCount + 1}/10 次测试 - 重新开始
                                </Text>
                            </>
                        ) : (
                            <>
                                <Text className="text-2xl text-gray-600 mb-5">请等待...</Text>
                                <Text className="text-lg text-blue-600 font-bold">
                                    第 {testCount + 1}/10 次测试
                                </Text>
                            </>
                        )}
                    </View>
                )}

                {testState === 'testing' && currentColor && (
                    <View className="items-center">
                        <View
                            className="rounded-full mb-5 shadow-lg"
                            style={{
                                width: 200,
                                height: 200,
                                backgroundColor: colorValues[currentColor]
                            }}
                        />
                        <Text className="text-2xl font-bold text-gray-800 mb-5">
                            {colorNames[currentColor]}
                        </Text>
                        <Text className="text-lg text-blue-600 font-bold">
                            第 {testCount + 1}/10 次测试
                        </Text>
                    </View>
                )}

                {testState === 'finished' && (
                    <View className="items-center bg-white p-5 rounded-xl shadow-sm max-w-[90%]">
                        <Text className="text-2xl font-bold text-blue-600 mb-4">测试完成！</Text>
                        <Text className="text-xl font-bold text-gray-800 mb-3">
                            平均反应时间: {averageTime.toFixed(0)} 毫秒
                        </Text>
                        {/*<Text className="text-base text-gray-600 mb-5">*/}
                        {/*    {averageTime < 300 ? '反应速度：优秀' :*/}
                        {/*        averageTime < 500 ? '反应速度：良好' : '反应速度：需要改善'}*/}
                        {/*</Text>*/}

                        <View className="w-full mb-5">
                            <Text className="text-base font-bold text-gray-800 mb-3">详细结果：</Text>
                            {reactionTimes.map((time, index) => (
                                <Text key={index} className="text-sm text-gray-600 mb-1">
                                    第 {index + 1} 次: {time} 毫秒
                                </Text>
                            ))}
                        </View>

                        <View className="flex-row gap-2">
                            <TouchableOpacity className="bg-orange-500 px-4 py-3 rounded-lg" onPress={startTest}>
                                <Text className="text-white text-base font-bold">重新测试</Text>
                            </TouchableOpacity>
                            <TouchableOpacity className="bg-green-500 px-4 py-3 rounded-lg" onPress={finishTest}>
                                <Text className="text-white text-base font-bold">完成</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                )}
            </View>

            {/* 颜色按钮区域 */}
            {(testState === 'testing' || testState === 'waiting') && (
                <View className="flex-row mb-12 pb-36 justify-evenly px-2 gap-2">
                    <TouchableOpacity
                        className={`${className} ${
                            showError ? 'opacity-60' : 'opacity-100'
                        }`}
                        style={{backgroundColor: colorValues.red}}
                        onPress={() => handleColorClick('red')}
                        disabled={testState !== 'testing'}
                    >
                        <Text className="text-white text-xl font-bold">红色</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        className={`${className} ${
                            showError ? 'opacity-60' : 'opacity-100'
                        }`}
                        style={{backgroundColor: colorValues.green}}
                        onPress={() => handleColorClick('green')}
                        disabled={testState !== 'testing'}
                    >
                        <Text className="text-white text-xl font-bold">绿色</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        className={`${className} ${
                            showError ? 'opacity-60' : 'opacity-100'
                        }`}
                        style={{backgroundColor: colorValues.blue}}
                        onPress={() => handleColorClick('blue')}
                        disabled={testState !== 'testing'}
                    >
                        <Text className="text-white text-xl font-bold">蓝色</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        className={`${className} ${
                            showError ? 'opacity-60' : 'opacity-100'
                        }`}
                        style={{backgroundColor: colorValues.yellow}}
                        onPress={() => handleColorClick('yellow')}
                        disabled={testState !== 'testing'}
                    >
                        <Text className="text-white text-xl font-bold">黄色</Text>
                    </TouchableOpacity>
                </View>
            )}

            {/* 检测完成提示对话框 */}
            {showCompletionDialog && (
                <View style={styles.dialogOverlay}>
                    <View style={styles.dialogContainer}>
                        <Text style={styles.dialogTitle}>检测完成</Text>
                        <Text style={styles.dialogMessage}>
                            您的检测已完成，结果已保存。是否继续检测或返回？
                        </Text>
                        <View style={styles.dialogButtonContainer}>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.continueButton]}
                                onPress={() => setShowCompletionDialog(false)}
                            >
                                <Text style={styles.continueButtonText}>继续检测</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.backButton]}
                                onPress={finishTest}
                            >
                                <Text style={styles.backButtonText}>返回</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 10,
        padding: 20,
        width: '80%',
        maxWidth: 300,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 15,
        textAlign: 'center',
        color: '#0a7ea4',
    },
    dialogMessage: {
        fontSize: 16,
        marginBottom: 20,
        textAlign: 'center',
        color: '#333',
        lineHeight: 22,
    },
    dialogButtonContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
    },
    dialogButton: {
        paddingVertical: 10,
        paddingHorizontal: 20,
        borderRadius: 5,
        minWidth: 80,
    },
    continueButton: {
        backgroundColor: '#0a7ea4',
    },
    backButton: {
        backgroundColor: '#f0f0f0',
    },
    continueButtonText: {
        color: 'white',
        textAlign: 'center',
        fontWeight: 'bold',
    },
    backButtonText: {
        color: '#333',
        textAlign: 'center',
        fontWeight: 'bold',
    },
});

export default ReactionDevice;